//
//  CPAudioPlayer.m
//  GHTestWebViewDemo
//
//  Created by collegepre on 16/9/18.
//  Copyright © 2016年 张冠华. All rights reserved.
//

#import "CPAudioPlayer.h"
#import <AudioToolbox/AudioToolbox.h>

@interface CPAudioPlayer() <AVAudioPlayerDelegate>

@end

@implementation CPAudioPlayer

- (void)continuePlaying{
    if (self.audioPath && ![self.audioPath isEqualToString:@""]) {
        [self.player play];
    }
}

/**
 *  是否正在播放录音
 *
 *  @return
 */
- (BOOL)isPlaying
{
    return [_player isPlaying];
}

- (void)pausePlayingBlock:(void (^)())completion
{
    if (_player.isPlaying)
    {
        [_player pause];
        self.isPausePlaying = YES;
        if (completion)
        {
            completion();
        }
    }
}

#pragma mark 开始播放
- (void)startPlayingWithName:(NSString *)filePath block:(void (^)())completion
{
    
    NSURL *url = [NSURL fileURLWithPath:filePath];
    NSFileManager *manger = [NSFileManager defaultManager];
    if (![manger fileExistsAtPath:filePath])
    {
        completion();
        return;
    }
    self.audioPath = filePath;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:&err];//此处需要恢复设置回放标志，否则会导致其它播放声音也会变小
    [audioSession setActive:YES error:nil];
    
    NSError *playerIninError;
    NSData *audioData = [NSData dataWithContentsOfFile:filePath];
    
    // AVFileTypeWAVE   AVFileTypeMPEGLayer3
    _player = [[AVAudioPlayer alloc] initWithData:audioData fileTypeHint:AVFileTypeMPEGLayer3 error:&playerIninError];
    if (playerIninError) {
        completion();
        //        playerError(playerIninError);
        _player = [[AVAudioPlayer alloc] initWithData:audioData fileTypeHint:AVFileTypeWAVE error:&playerIninError];
        if (playerIninError) {
            return;
        }
    }
    
    
    _player.delegate = self;
    _player.volume = 1;
    
    [_player setNumberOfLoops:0];
    [_player prepareToPlay];
    [_player play];
    self.isPausePlaying = NO;
    if (completion) {
        self.playComplete = ^(BOOL suc){
            completion();
        };
    }
}

- (void)startPlayingWithName:(NSString *)filePath numberOfLoops:(NSInteger)loops block:(void (^)())completion{
    NSURL *url = [NSURL fileURLWithPath:filePath];
    NSFileManager *manger = [NSFileManager defaultManager];
    if (![manger fileExistsAtPath:filePath])
    {
        completion();
        return;
    }
    self.audioPath = filePath;
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryPlayback error:&err];
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];  //此处需要恢复设置回放标志，否则会导致其它播放声音也会变小
    [session setActive:YES error:nil];
    
    _player.delegate = self;
    _player.volume = 1;
    
    [_player setNumberOfLoops:loops];
    [_player prepareToPlay];
    [_player play];
    self.isPausePlaying = NO;
    if (completion) {
        self.playComplete = ^(BOOL suc){
            completion();
        };
    }
}


- (void)startPlayPlaySystemSoundWithURLPath:(NSString *)soundPath{
    NSURL *url2 = [NSURL URLWithString:soundPath];
    SystemSoundID systemSound;
    
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url2, &systemSound);
    
    AudioServicesPlaySystemSound(systemSound);
}

#pragma mark 停止播放
- (void)stopPlayingBlock:(void (^)())completion
{
    if ([_player isPlaying])
    {
        [_player stop];
        self.isPausePlaying = NO;
        if (completion)
        {
            completion();
        }
    }
}

- (void)pausePlaying
{
    if (_player.isPlaying)
    {
        [_player pause];
        self.isPausePlaying = YES;
    }
}


#pragma mark 开始播放
- (void)startPlayingWithName:(NSString *)filePath
{
    NSURL *url = [NSURL fileURLWithPath:filePath];
    NSFileManager *manger = [NSFileManager defaultManager];
    if (![manger fileExistsAtPath:filePath])
    {
        //        [MBProgressHUD showError:@"音频文件不存在" toView:sel ];
        return;
    }
    
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];  //此处需要恢复设置回放标志，否则会导致其它播放声音也会变小
    [session setActive:YES error:nil];
    
    self.audioPath = filePath;
    
    NSError *error;
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    if (!error) {
        _player.delegate = self;
        [_player setNumberOfLoops:0];
        [_player prepareToPlay];
        _player.volume = 1;
        [_player play];
        self.isPausePlaying = NO;
    }
}

#pragma mark 停止播放
- (void)stopPlaying
{
    if ([_player isPlaying])
    {
        [_player stop];
        self.isPausePlaying = NO;
        if (self.stopPlayCallback) {
            self.stopPlayCallback();
        }
    }
}

/**
 *  AVAudioPlayer代理方法
 */

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if (self.playComplete)
    {
        self.playComplete(YES);
    }
    
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error{
    NSLog(@"audioPlayerDecodeErrorDidOccur- %@",error);
}


@end
